﻿package com.gamemeal.facebook {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	/**
	 * @author Colin
	 */
	public final class FacebookApp extends EventDispatcher{
		namespace facebookNS = "http://api.facebook.com/1.0/";

		private var api_key:String;
		private var private_key:String;
		private var token:String;
		private var restServer:String;
		private var v:String;

		public var session_key:String;
		public var uid:String;

		public function FacebookApp(api_key:String,private_key:String,token:String="",session_key:String="",uid:String="",v:String="1.0",restServer:String="http://api.facebook.com/restserver.php"){
			this.api_key = api_key;
			this.private_key = private_key;
			this.token = token;
			this.restServer = restServer;
			this.v=v;
			this.session_key = session_key;
			this.uid = uid;

			if(session_key==null||session_key==""){
				if(token==null||token==""){
					request(Auth.createToken(api_key,v),onTokenCreated);
				}else{
					request(Auth.getSession(api_key,v,token),onSessionCreated);
				}
			}else{
				dispatchEvent(new FacebookAppEvent(FacebookAppEvent.READY));
			}
		}

		public function request(methodArguments:Array,callbackFunction : Function) : void {
			var request:URLRequest = new URLRequest(restServer);
			request.data = arrayToURLVariables(methodArguments);

			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, callbackFunction);
			loader.load(request);
		}

		private function onTokenCreated(e:Event):void{
			token = XML(e.target.data);
			request(Auth.getSession(api_key,v,token),onSessionCreated);
		}

		private function onSessionCreated(e:Event):void{
			var respond:XML = XML(e.target.data);
			session_key = respond.facebookNS::session_key;
			uid = respond.facebookNS::uid;

			dispatchEvent((session_key!="")?
					new FacebookAppEvent(FacebookAppEvent.READY):
					new FacebookAppEvent(FacebookAppEvent.ERROR,'sessionError')
			);
		}

		private function sign(args:Array):String{
			var params:Array = new Array();
		    for (var key:String in args) {
	         	var value:String = args[key];
	         	if (key !== 'sig') {
		         	params.push(key + '=' + value);
	         	}
		    }
	     	params.sort();
	     	var valueToHash:String = params.join('');
	     	valueToHash += private_key;
			return MD5.encrypt(valueToHash);
		}

		private function arrayToURLVariables(ary:Array,requireSign:Boolean=true):URLVariables{
			var postData : URLVariables = new URLVariables();
			for(var name:String in ary){
				postData[name] = ary[name];
			}

			if(requireSign==true)postData['sig']= sign(ary);

			return postData;
		}
	}
}